package com.lt.lumentracks.controller.common;

import com.aliyuncs.exceptions.ClientException;
import com.lt.lumentracks.constant.FileConstant;
import com.lt.lumentracks.entity.vo.common.Result;
import com.lt.lumentracks.service.common.FileUploadService;
import com.lt.lumentracks.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/common/file")
public class FileController {

    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private FileUploadService fileUploadService;


    /**
     * 单文件上传（帖子相关）
     * @param file 上传的文件
     */
    @PostMapping("/upload")
    public Result<String> uploadFiles(@RequestPart("file") MultipartFile file) {
        try{
            return fileUploadService.uploadFiles_post(file);
        } catch (Exception e) {
            log.error("文件上传失败：", e);
        }
        return Result.error("文件上传失败");
    }


    /**
     * 单文件上传（用户头像相关）
     * @param file 上传的文件
     */
    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatarFiles(@RequestPart("file") MultipartFile file) {
        try{
            String filePath = aliOSSUtils.upload(file, FileConstant.OSS_DIRECTORY_NAME_USER_PIC); //文件的请求路径
            return Result.success(filePath);
        } catch (Exception e) {
            log.error("文件上传失败：", e);
        }
        return Result.error("文件上传失败");
    }


    /**
     * 文件删除
     * @param fileFullPath  要删除的文件的全路径，例如："https://存储桶名字.阿里云oss服务器地址/目录名(可以为空也可以多层)/文件名"
     */
    @PostMapping("/delete")
    public Result<String> deleteFile(@RequestParam("fileFullPath") String fileFullPath) throws ClientException {
        boolean res = aliOSSUtils.deleteObject(fileFullPath);
        if(res){
            return Result.success("删除成功");
        }else {
            return Result.error("删除失败");
        }
    }
}
